<?php

declare(strict_types=1);

namespace App\Traits\Model\Goods;

use App\Scopes\Goods\Good as GoodScope;
use App\Model\Goods\GoodImage as GoodImageModel;
use Hyperf\Database\Model\Relations\HasMany;

trait Good
{
    /**
     * The "booting" method of the model.
     */
    protected function boot():void
    {
        parent::boot();
        static::addGlobalScope(new GoodScope);
    }

    /**
     * 店铺
     * @param $value
     */
    public function setShopIdAttribute($value)
    {
        if (!$value) {
            $value = match (getApp()) {
                'api' => getShop('id')
            };
        }

        $this->attributes['shop_id'] = $value;
    }

    /**
     * 商品图片
     * @return HasMany
     */
    public function images():HasMany
    {
        return $this->hasMany(GoodImageModel::class);
    }

    /**
     * 获取内容
     * @return string
     */
    public function getContentAttribute($value):string
    {
        return $value?htmlspecialchars_decode($value):'';
    }

    /**
     * 给图片解码
     * @param $value
     * @return string
     */
    public function getImageAttribute($value):string
    {
        return $value?urldecode($value):'';
    }
}
